package com.yjc.drygoods.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yjc.common.constant.ExchangeDetailStatusEnum;
import com.yjc.common.utils.R;
import com.yjc.drygoods.ware.entity.*;
import com.yjc.drygoods.ware.exception.NotExitStockException;
import com.yjc.drygoods.ware.exception.OldTimersException;
import com.yjc.drygoods.ware.feign.ProductFeignService;
import com.yjc.drygoods.ware.service.*;
import com.yjc.drygoods.ware.to.SpuInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Not;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjc.common.utils.PageUtils;
import com.yjc.common.utils.Query;

import com.yjc.drygoods.ware.dao.ExchangeDetailDao;
import org.springframework.util.StringUtils;

@Slf4j
@Service("exchangeDetailService")
public class ExchangeDetailServiceImpl extends ServiceImpl<ExchangeDetailDao, ExchangeDetailEntity> implements ExchangeDetailService {

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WareSpuService wareSpuService;

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareInfoService wareInfoService;

    @Autowired
    BatchesService batchesService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<ExchangeDetailEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(i -> i.eq("exchange_id", key).or().or().like("spu_name", key));
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status", status);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }
        IPage<ExchangeDetailEntity> page = this.page(
                new Query<ExchangeDetailEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 新增换货需求
     *
     * @param exchangeDetail
     */
    @Override
    public void saveExchangeDetail(ExchangeDetailEntity exchangeDetail) {
        // 传过来的有spuId、
        // 交换后货物的仓库id(wareId)、
        Long spuId = exchangeDetail.getSpuId();
        Long wareId = exchangeDetail.getWareId();

        //获取指定spuId干货信息
        R rSpuInfo = productFeignService.spuInfo(spuId);
        if (rSpuInfo.getCode() != 0) {
            throw new RuntimeException("干货远程服务调用失败");
        }
        SpuInfoTo spuInfo = rSpuInfo.getData("spuInfo", new TypeReference<SpuInfoTo>() {
        });
        //获取指定spuId干货的所有仓库库存信息
        List<WareSpuEntity> wareSpuList = wareSpuService.list(new QueryWrapper<WareSpuEntity>().eq("spu_id", spuId));
        if (wareSpuList == null || wareSpuList.size() <= 0) {
            throw new NotExitStockException();
        }
        //统一该spuId干货在所有仓库的库存存储信息
        WareSpuEntity wareSpuTotalStock = new WareSpuEntity();
        for (WareSpuEntity wareSpu : wareSpuList) {
            wareSpuTotalStock.setStock((wareSpuTotalStock.getStock() == null ? 0 : wareSpuTotalStock.getStock()) + wareSpu.getStock());
            wareSpuTotalStock.setStockLocked((wareSpuTotalStock.getStockLocked() == null ? 0 : wareSpuTotalStock.getStockLocked()) + wareSpu.getStockLocked());
        }

        //1.设置需换干货名称
        exchangeDetail.setSpuName(spuInfo.getSpuName());
        //2.设置需换干货数量
        Double stockNum = wareSpuTotalStock.getStock() - wareSpuTotalStock.getStockLocked();
        if (stockNum < 1) {
            throw new NotExitStockException("干货库存不足，无法进行换货操作");
        }
        int count = this.count(new QueryWrapper<ExchangeDetailEntity>()
                .eq("spu_id", exchangeDetail.getSpuId())
                .and(i -> i.ne("status", ExchangeDetailStatusEnum.FINISHED.getCode()).ne("status", ExchangeDetailStatusEnum.BUYERROR.getCode())));
        if (count >= 1) {
            throw new OldTimersException("已存在该干货的换货需求，请勿重复添加~");
        }
        exchangeDetail.setSpuNum(wareSpuTotalStock.getStock() - wareSpuTotalStock.getStockLocked());
        //3.设置需换货物的批次(oriBatch)
        BatchesEntity spuBatch = batchesService.getSpuBatch(spuId);
        exchangeDetail.setOriBatch(spuBatch.getBatch());
        //4.设置需换干货单价
        exchangeDetail.setOriSpuPrice(spuBatch.getSpuPrice());
        //5.设置要进行换货操作的供货商id(supplierId)
        exchangeDetail.setSupplierId(spuBatch.getSupplierId());
        //6.设置要进行换货操作的供货商名称(supplierName)
        exchangeDetail.setSupplierName(spuBatch.getSupplierName());
        //7.设置需换干货总金额
        exchangeDetail.setOriSpuTotalPrice(exchangeDetail.getOriSpuPrice().multiply(new BigDecimal((exchangeDetail.getSpuNum()).toString())));
        //8.设置存放交换后货物的仓库名称（通过陈年老货管理新增的换货需求不会传wareId）
        WareInfoEntity wareInfo = wareInfoService.getById(wareId == null ? 1L : wareId);
        exchangeDetail.setWareName(wareInfo.getName());
        //9.设置更新时间
        exchangeDetail.setUpdateTime(new Date());
        //10.设置状态
        exchangeDetail.setStatus(ExchangeDetailStatusEnum.CREATED.getCode());
        log.info("exchangeDetail:{}", exchangeDetail);
        this.save(exchangeDetail);
    }

    @Override
    public List<ExchangeDetailEntity> listDetailByExchangeId(Long id) {

        return this.list(new QueryWrapper<ExchangeDetailEntity>().eq("exchange_id", id));
    }

}